package com.example.mq.mqserver;

import com.example.mq.common.BinaryTool;
import com.example.mq.common.Consumer;
import com.example.mq.common.ConsumerEnv;
import com.example.mq.common.MqException;
import com.example.mq.common.communication.*;
import com.example.mq.mqserver.core.BasicProperties;
import com.example.mq.mqserver.core.MSGQueue;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 这个类就是消息队列的本体服务器
 * 本质就是一个TCP服务器
 */
@Slf4j
public class BrokerServer {
    private ServerSocket serverSocket;
    //当前只考虑一个BrokerServer上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //使用一个哈希表来表示当前所有的会话（就是当前有哪些客户端正在与服务器进行通信）
    //key-channelId  value-Socket（每一个socket就代表一个客户端）
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    //引入一个线程池，来处理多个客户端的请求
    private ExecutorService executorService;
    //引入一个变量，控制当前服务器的是否运行
    private volatile boolean runnable = true;

    private ConcurrentHashMap<String,BasicConsumerArguments> requestMap = new ConcurrentHashMap<>();

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    //服务器启动
    public void start() throws IOException {
        log.info("[BrokerServer] 启动");
        executorService = Executors.newCachedThreadPool();
        try {
            while(runnable) {
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException | ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }catch (SocketException e) {
            log.info("[BrokerServer] 服务器停止运行");
        }

    }

    //通过这方法来处理一个客户端的连接
    //但在这个连接中可能设计很多的请求与响应
    private void processConnection(Socket clientSocket) throws IOException, ClassNotFoundException {

        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //由于需要按照特定格式进行数据的读取，所以还需要使用下面的stream类
            try(DataInputStream dataInputStream = new DataInputStream(inputStream);
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request,clientSocket);
                    //3.返回响应
                    writeResponse(dataOutputStream,response);
                }
            }
        }catch (EOFException | SocketException e) {
            //如果当前是这个两个异常，代表要么文件读到末尾，要么socket已经关闭
            //那么此时服务器可以停止了（借助该异常）
            log.info("[BrokerServer] connection关闭! 客户端的地址: " + clientSocket.getInetAddress().toString() +
                    ": " + clientSocket.getPort());
            String channelId = null;
            for(Map.Entry<String,Socket> entry : sessions.entrySet()) {
                if(entry.getValue().equals(clientSocket)) {
                    channelId = entry.getKey();
                    break;
                }
            }
            BasicConsumerArguments basicConsumerArguments = requestMap.get(channelId);
            if(basicConsumerArguments != null) {
                System.out.println(basicConsumerArguments.toString());
                String queueName = virtualHost.getVirtualHostName() + basicConsumerArguments.getQueueName();
                System.out.println("queueName: " + queueName);
                MSGQueue queue = virtualHost.getMemoryDataManage().getQueue(queueName);
                if (queue == null) {
                    log.info("当前队列不存在");
                    throw new IOException("当前队列不存在");
                }
                ConsumerEnv consumerEnv = new ConsumerEnv(basicConsumerArguments.getConsumerTag(), queueName,
                        basicConsumerArguments.isAutoAck(), basicConsumerArguments.getConsumer());
                queue.removeConsumerEnv(consumerEnv);
            }
        } catch (IOException | ClassNotFoundException e) {            //如果是该异常，那么是在写读数据过程中出现了问题
            e.printStackTrace();
            log.info("[BrokerServer] 出现异常!");
        }finally {
            //关闭clientSocket
            try {
                clientSocket.close();
                //一个TCP连接里面有多个channel，还需要清理掉与该socket相关的所有channel
                clearSocketChannel(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //该方法就是遍历上述哈希表，然后将里面与clientSocket相关联的所有的channel进行删除
    private void clearSocketChannel(Socket clientSocket) {
        List<String> toDelete = new LinkedList<>();
        for(Map.Entry<String,Socket> entry : sessions.entrySet()) {
            if(entry.getValue().equals(clientSocket)) {
                toDelete.add(entry.getKey());
            }
        }
        for(String channelId : toDelete) {
            sessions.remove(channelId);
        }
        log.info("[BrokerServer] 删除与socket相关channel成功");
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException, ClassNotFoundException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if(n != request.getLength()) {
            throw new IOException("[BrokerServer] 数据解析出现错误");
        }
        request.setPayload(payload);
        log.info("[BrokerServer] 读取请求成功 type: " + request.getType() + ",length: " + n);
        return request;
    }

    private Response process(Request request,Socket clientSocket) throws IOException, ClassNotFoundException {
        //1.首先解析一下当前请求中的payload数据
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());

        //2.根据请求中type的类型解析一下当前请求是要干啥
        int type = request.getType();
        boolean ok = true;
        if(type == 0x1) {
            //创建channel
            sessions.put(basicArguments.getChannelId(),clientSocket);
        }else if(type == 0x2) {
            //销毁channel
            sessions.remove(basicArguments.getChannelId());
        }else if(type == 0x3) {
            //创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getType(),arguments.isDurable(),
                    arguments.isAutoDelete(),arguments.getArguments());
        }else if(type == 0x4) {
            //销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        }else if(type == 0x5) {
            //创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isAutoDelete(),
                    arguments.isExclusive(),arguments.getArguments());
        }else if(type == 0x6) {
            //销毁队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        }else if(type == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(),arguments.getExchangeName(),arguments.getBindingKey());
        }else if(type == 0x8) {
            //销毁绑定
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnBind(arguments.getQueueName(),arguments.getExchangeName());
        }else if(type == 0x9) {
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(),arguments.getRoutingKey(),
                    arguments.getBasicProperties(),arguments.getBody());
        }else if(type == 0xa) {
            //订阅消息
            BasicConsumerArguments arguments = (BasicConsumerArguments) basicArguments;
            //该回调函数的用处是：当有生产者往对应队列中生产了消息，服务器就可以将当前队列中的消息推送给消费者客户端
            Consumer consumer = new Consumer() {
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                        //(1)首先需要知道当前推送的消费者是谁
                        //其实这里的channelId就是当前消费者的一个身份标识，也就是consumerTag
                        //所以就需要从存储的哈希表(sessions)中找到当前消费者所对应的socket，进而将消息给推送回去
                        Socket socket = sessions.get(consumerTag);
                        if(socket == null) {
                            //删除当前队列中订阅消息的消费者
                            ConsumerEnv consumerEnv = virtualHost.getMemoryDataManage().getConsumer(consumerTag);
                            MSGQueue queue = virtualHost.getMemoryDataManage().getQueue(consumerEnv.getQueueName());
                            queue.removeConsumerEnv(consumerEnv);
                            throw new MqException("[BrokerServer] 订阅消息的客户端已断开连接");
                        }
                        //(2)构造payload
                        SubScribeReturns scribeReturns = new SubScribeReturns();
                        scribeReturns.setBody(body);
                        scribeReturns.setConsumerTag(consumerTag);
                        scribeReturns.setBasicProperties(basicProperties);
                        scribeReturns.setOk(true);
                        //由于这里只有响应没有请求，暂时不需要要rid进行对应
                        scribeReturns.setRid(arguments.getRid());
                        scribeReturns.setChannelId(consumerTag);
                        //(3)构造响应
                        Response response = new Response();
                        try {
                            byte[] payload = BinaryTool.toBytes(scribeReturns);
                            response.setPayload(payload);
                            response.setLength(payload.length);
                            response.setType(0xc);
                            //(4)写回当前响应
                            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                            writeResponse(dataOutputStream,response);
                            log.info("[BrokerServer] 消息消费响应构造完成 type = " + response.getType() + "length = " + response.getLength());
                        } catch (IOException e) {
                            e.printStackTrace();
                            log.info("[BrokerServer] 序列化失败|写回响应失败");
                        }
                }
            };
            ok = virtualHost.basicConsumer(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),consumer);
            arguments.setConsumer(consumer);
            requestMap.put(arguments.getChannelId(),arguments);
        }else if(type == 0xb) {
            //手动确认
            BasicAckArguments arguments = (BasicAckArguments)basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(),arguments.getMessageId());
        }else {
            throw new MqException("[BrokerServer] 未知的type type: " + type);
        }
        //3.构造响应并返回
        Response response = new Response();
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        log.info("[Response] rid: " + basicArguments.getRid() + ",channelId: " + basicArguments.getChannelId() +
                ",type: " + response.getType() + ",length:" + response.getLength());
        return response;

    }
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        log.info("[BrokerServer] 写入响应完成! type: " + response.getType() + ",length: " + response.getLength());
        //记得刷新
        dataOutputStream.flush();
    }

    //一般来说，都是直接kill掉进程
    //但这个写了一个stop方法，主要是为了后续的单元测试
    public void stop() throws IOException {
        log.info("[BrokerServer] 停止");
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }
}
